<?php

namespace app\service;

// 宇宙列车服务
use app\model\FactoryIngredient;
use app\model\Material;
use app\model\User;
use app\model\UserFactory;
use app\model\UserIngredient;
use app\model\UserSpaceTrain;
use app\model\UserWish;
use extend\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class UserSpaceTrainService extends BaseService
{

    // 获取用户宇宙列车
    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function get_user_space_train($user_id): array
    {
        //查询用户宇宙列车
        $user_space_train_list = (new UserSpaceTrain())->where('user_id', $user_id)->select();

        $user = (new User())->find($user_id);

        if (!$user) {
            return $this->returnFail('用户不存在');
        }
        //当前的城堡等级
        $user_castle_lv = $user->castle_lv;

        //获取列车额解锁限制
        $unlock_config = SPACE_TRAIN_CONFIG['解锁限制'];

        //可以解锁的列车数量
        $unlock_num = 0;

        foreach ($unlock_config as $key => $value) {
            if ($user_castle_lv >= $key) {
                $unlock_num = $value;
            }
        }

        //如果当前的列车数量小于解锁的列车数量
        if (!$unlock_num) {
            return $this->returnFail('未达到解锁条件');
        }


        $task_config = array_slice(SPACE_TRAIN_CONFIG['任务列表'], 0, $unlock_num);


        $type_list = [];
        foreach ($task_config as $type) {
            $is_exist = false;
            foreach ($user_space_train_list as $user_space_train) {
                if ($user_space_train['type'] == $type) {
                    $type_list[] = $user_space_train->toArray();
                    $is_exist = true;
                }
            }
            //任务不存在 生成一个任务
            if (!$is_exist) {
                $res = $this->create_space_train($user_id, $type);
                if (!$res['code']) {
                    return $res;
                }
                $type_list[] = $res['data'];
            }
        }

        $user_ingredient_list = (new UserIngredient())->where('user_id', $user_id)->select();

        $user_ingredient_map = [];

        foreach ($user_ingredient_list as $user_ingredient) {
            $user_ingredient_map[$user_ingredient->ingredients_id] = $user_ingredient->num;
        }

        foreach ($type_list as &$item) {

            $item['extra'] = json_decode($item['extra'], true);

            //我当前的材料数量
            foreach ($item['extra'] as &$extra) {
                $extra['my_num'] = $user_ingredient_map[$extra['id']];
            }


            $item['reward'] = json_decode($item['reward'], true);
        }

        return $this->returnSuccess($type_list);


    }

    /**
     * 出发
     * @throws DbException
     */
    public function start($user_id, $user_space_train_id): array
    {

        //查询用户宇宙列车
        $user_space_train = (new UserSpaceTrain())->where('user_id', $user_id)->where('id', $user_space_train_id)->find();

        if (!$user_space_train) {
            return $this->returnFail('任务不存在');
        }

        if ($user_space_train->status != SPACE_TRAIN_CONFIG['列车状态']['未发车']) {
            return $this->returnFail('任务已开始');
        }

        if ($user_space_train->state != SPACE_TRAIN_CONFIG['领取状态']['未发放']) {
            return $this->returnFail('任务已结束');
        }

        $user_space_train->status = SPACE_TRAIN_CONFIG['列车状态']['进行中'];
        $res = $user_space_train->save();
        if ($res) {
            return $this->returnSuccess($user_space_train->toArray());
        } else {
            return $this->returnFail('任务开始失败');
        }

    }

    /**
     *  完成
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function complete($user_id, $user_space_train_id): array
    {
        $user_space_train = (new UserSpaceTrain())->where('user_id', $user_id)->where('id', $user_space_train_id)->find();

        if (!$user_space_train) {
            return $this->returnFail('任务不存在');
        }

        //查询任务需要的材料

        $user_space_train->extra = json_decode($user_space_train->extra, true);

        foreach ($user_space_train->extra as $extra) {
            $ingredients_id = $extra['id'];
            $ingredients_num = $extra['num'];
            $user_ingredients = (new UserIngredient())::where('ingredients_id', $ingredients_id)->where('user_id', $user_id)->find();

            if (!$user_ingredients) {
                return $this->returnFail('材料不足');
            }

            if ($user_ingredients->num < $ingredients_num) {
                return $this->returnFail('材料不足');
            }
            $user_ingredients->num = $user_ingredients->num - $ingredients_num;
            $user_ingredients->save();
        }


        //发放奖励
        $user_space_train->reward = json_decode($user_space_train->reward, true);

        //增加金币
        $res_user_money = (new UserService())->change_money($user_id, $user_space_train->reward['coin'], USER_CAPITAL_TYPE['金币'], USER_CAPITAL_STATUS['增加']);
        if (!$res_user_money['code']) {
            return $res_user_money;
        }
        $data = [
            'coin' => $user_space_train->reward['coin'],
            'user_info' => (new UserService())->get_user_info($user_id)
        ];

        //删除
        (new UserWish())::destroy($user_space_train->id);


        return $this->returnSuccess($data);
    }


    /**
     * 生成一个任务
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function create_space_train($user_id, $type): array
    {


        //先判断是不是已经存在了该任务
        $is_exist = (new UserSpaceTrain())->where('user_id', $user_id)->where('type', $type)->find();
        if ($is_exist) {
            return $this->returnFail('任务已存在');
        }
        $user_space_train = new UserSpaceTrain();


        $user_space_train->user_id = $user_id;
        $user_space_train->type = $type;


        $extra = [];
        //查询我已经拥有的工厂
        $user_factory_list = (new UserFactory())->field('factory_id')->where('user_id', $user_id)->where('state', '<>', FACTORY_STATE['已购买'])->select();


        $user_factory_ids = [];
        foreach ($user_factory_list as $user_factory) {
            $user_factory_ids[] = $user_factory->factory_id;
        }

        //获取可以加工的全部材料
        $factory_ingredient_list = (new FactoryIngredient())->field('id')->whereIn('factory_id', $user_factory_ids)->select();

        //材料id
        $ingredient_ids = [];
        foreach ($factory_ingredient_list as $factory_ingredient) {
            $ingredient_ids[] = $factory_ingredient->id;
        }


        //随机抽取2-3件 生产材料的1-3份

        $random_total = [3, 5];

        $ingredient_list = Random::lottery($ingredient_ids, $random_total);

        $random_num = [1, 2, 3];
        $ingredient = [];
        $ingredient_id = [];
        foreach ($ingredient_list as $item) {
            $index = Random::lottery($random_num);
            $num = $random_num[$index];
            $extra[] = [
                'id' => $ingredient_ids[$item],
                'num' => $num
            ];
            $ingredient[$ingredient_ids[$item]] = $num;
            $ingredient_id[] = $ingredient_ids[$item];

        }

        $user_space_train->extra = json_encode($extra);
        //该材料建筑或升级所需金币的1%x份数的金币
        $material = (new Material())->whereIn('ingredients_id', $ingredient_id)->select();

        $coin = 0;
        foreach ($material as $item) {
            $coin = $coin + $item->need_coin * 0.01 * $ingredient[$item->ingredients_id];
        }

        $reward = [
            //向下取整
            'coin' => intval($coin)
        ];

        $user_space_train->reward = json_encode($reward);
        $res = $user_space_train->save();
        if ($res) {
            return $this->returnSuccess($user_space_train->toArray());
        } else {
            return $this->returnFail('创建任务失败');
        }


    }


}